/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

class Solution
{
public:
    int countNodes(TreeNode* root)
    {
        if (root == nullptr)
            return 0;
        
        if (root->left  == nullptr)
            return 1;

        int layer = 0;
        int max_layer = std::log2(5*pow(10,4) + 1);
        TreeNode* last_node = root;

        while(layer <= max_layer)
        {
            layer++;
            if(last_node->left != nullptr)
                last_node = last_node->left;
            else
                break;
        }
        
        int loop = std::pow(2, layer-1);
        for (int i = 0; i < loop; i++)
        {
            last_node = root;
            int mask = (1<<layer-1) - 1 - i; // eg: layer=4, action:111 110 101 100 ... (1-left,0-right), last layer num = 8
            for (int j = 0; j < (layer-1); j++)
            {
                if((mask >> (layer-2-j)) & 0x1 == 1)
                {
                    if (last_node->left == nullptr)
                       return i + pow(2,layer-1) - 1;
                    else
                        last_node = last_node->left;
                }
                else
                {
                    if (last_node->right == nullptr)
                       return i + pow(2,layer-1) - 1;
                    else
                        last_node = last_node->right;
                }
            }   
        }

        return pow(2,layer) - 1;
    }
};
